package com.zhentao.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zhentao.config.Result;
import com.zhentao.pojo.*;
import com.zhentao.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 统计报表控制器
 * 
 * @author zhentao
 */
@RestController
@RequestMapping("tea/statistics")
public class StatisticsController {

    @Autowired
    private TcUserService userService;
    
    @Autowired
    private TcClassService classService;
    
    @Autowired
    private TcHomeworkService homeworkService;
    
    @Autowired
    private TcScoreService scoreService;
    
    @Autowired
    private TcCheckinService checkinService;

    /**
     * 获取总体统计信息
     */
    @GetMapping("overview")
    public Result<Map<String, Object>> getOverviewStatistics() {
        try {
            Map<String, Object> statistics = new HashMap<>();
            
            // 用户统计
            long totalUsers = userService.count();
            QueryWrapper<TcUser> teacherQuery = new QueryWrapper<>();
            teacherQuery.eq("identity", "老师");
            long teacherCount = userService.count(teacherQuery);
            
            QueryWrapper<TcUser> studentQuery = new QueryWrapper<>();
            studentQuery.eq("identity", "学生");
            long studentCount = userService.count(studentQuery);
            
            QueryWrapper<TcUser> parentQuery = new QueryWrapper<>();
            parentQuery.eq("identity", "家长");
            long parentCount = userService.count(parentQuery);
            
            statistics.put("totalUsers", totalUsers);
            statistics.put("teacherCount", teacherCount);
            statistics.put("studentCount", studentCount);
            statistics.put("parentCount", parentCount);
            
            // 班级统计
            long totalClasses = classService.count();
            QueryWrapper<TcClass> headteacherQuery = new QueryWrapper<>();
            headteacherQuery.eq("is_headteacher", 1);
            long headteacherClasses = classService.count(headteacherQuery);
            
            statistics.put("totalClasses", totalClasses);
            statistics.put("headteacherClasses", headteacherClasses);
            
            // 作业统计
            long totalHomework = homeworkService.count();
            QueryWrapper<TcHomework> activeHomeworkQuery = new QueryWrapper<>();
            activeHomeworkQuery.gt("deadline", new Date());
            long activeHomework = homeworkService.count(activeHomeworkQuery);
            
            statistics.put("totalHomework", totalHomework);
            statistics.put("activeHomework", activeHomework);
            
            // 成绩统计
            long totalScores = scoreService.count();
            statistics.put("totalScores", totalScores);
            
            // 打卡统计
            long totalCheckins = checkinService.count();
            QueryWrapper<TcCheckin> activeCheckinQuery = new QueryWrapper<>();
            Date now = new Date();
            activeCheckinQuery.le("start_time", now);
            activeCheckinQuery.ge("end_time", now);
            long activeCheckins = checkinService.count(activeCheckinQuery);
            
            statistics.put("totalCheckins", totalCheckins);
            statistics.put("activeCheckins", activeCheckins);
            
            return Result.success("获取总体统计信息成功", statistics);
        } catch (Exception e) {
            return Result.error("获取总体统计信息失败：" + e.getMessage());
        }
    }

    /**
     * 获取班级统计信息
     */
    @GetMapping("class/{classId}")
    public Result<Map<String, Object>> getClassStatistics(@PathVariable Integer classId) {
        try {
            Map<String, Object> statistics = new HashMap<>();
            
            // 班级基本信息
            TcClass tcClass = classService.getById(classId);
            if (tcClass == null) {
                return Result.error("班级不存在");
            }
            
            statistics.put("classInfo", tcClass);
            
            // 班级成员统计
            // 这里需要根据实际的班级成员表来统计
            // statistics.put("memberCount", memberCount);
            
            // 班级作业统计
            QueryWrapper<TcHomework> homeworkQuery = new QueryWrapper<>();
            homeworkQuery.eq("class_id", classId);
            long classHomeworkCount = homeworkService.count(homeworkQuery);
            
            QueryWrapper<TcHomework> activeHomeworkQuery = new QueryWrapper<>();
            activeHomeworkQuery.eq("class_id", classId);
            activeHomeworkQuery.gt("deadline", new Date());
            long activeHomeworkCount = homeworkService.count(activeHomeworkQuery);
            
            statistics.put("homeworkCount", classHomeworkCount);
            statistics.put("activeHomeworkCount", activeHomeworkCount);
            
            // 班级成绩统计
            QueryWrapper<TcScore> scoreQuery = new QueryWrapper<>();
            scoreQuery.eq("class_id", classId.toString());
            long scoreCount = scoreService.count(scoreQuery);
            
            statistics.put("scoreCount", scoreCount);
            
            // 班级打卡统计
            QueryWrapper<TcCheckin> checkinQuery = new QueryWrapper<>();
            checkinQuery.eq("class_id", classId);
            long checkinCount = checkinService.count(checkinQuery);
            
            statistics.put("checkinCount", checkinCount);
            
            return Result.success("获取班级统计信息成功", statistics);
        } catch (Exception e) {
            return Result.error("获取班级统计信息失败：" + e.getMessage());
        }
    }

    /**
     * 获取成绩统计信息
     */
    @GetMapping("score/{classId}/{subject}")
    public Result<Map<String, Object>> getScoreStatistics(@PathVariable Integer classId, 
                                                          @PathVariable String subject) {
        try {
            Map<String, Object> statistics = new HashMap<>();
            
            QueryWrapper<TcScore> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("class_id", classId.toString());
            queryWrapper.eq("subject", subject);
            List<TcScore> scores = scoreService.list(queryWrapper);
            
            if (scores.isEmpty()) {
                statistics.put("count", 0);
                statistics.put("average", 0);
                statistics.put("maxScore", 0);
                statistics.put("minScore", 0);
                return Result.success("获取成绩统计信息成功", statistics);
            }
            
            // 计算统计信息
            int count = scores.size();
            BigDecimal total = scores.stream()
                .map(TcScore::getScore)
                .reduce(BigDecimal.ZERO, BigDecimal::add);
            BigDecimal average = total.divide(BigDecimal.valueOf(count), 2, BigDecimal.ROUND_HALF_UP);
            
            BigDecimal maxScore = scores.stream()
                .map(TcScore::getScore)
                .max(BigDecimal::compareTo)
                .orElse(BigDecimal.ZERO);
            
            BigDecimal minScore = scores.stream()
                .map(TcScore::getScore)
                .min(BigDecimal::compareTo)
                .orElse(BigDecimal.ZERO);
            
            // 分数段统计
            Map<String, Long> scoreRanges = new HashMap<>();
            scoreRanges.put("优秀(90-100)", scores.stream().filter(s -> s.getScore().compareTo(new BigDecimal("90")) >= 0).count());
            scoreRanges.put("良好(80-89)", scores.stream().filter(s -> s.getScore().compareTo(new BigDecimal("80")) >= 0 && s.getScore().compareTo(new BigDecimal("90")) < 0).count());
            scoreRanges.put("中等(70-79)", scores.stream().filter(s -> s.getScore().compareTo(new BigDecimal("70")) >= 0 && s.getScore().compareTo(new BigDecimal("80")) < 0).count());
            scoreRanges.put("及格(60-69)", scores.stream().filter(s -> s.getScore().compareTo(new BigDecimal("60")) >= 0 && s.getScore().compareTo(new BigDecimal("70")) < 0).count());
            scoreRanges.put("不及格(0-59)", scores.stream().filter(s -> s.getScore().compareTo(new BigDecimal("60")) < 0).count());
            
            statistics.put("count", count);
            statistics.put("average", average);
            statistics.put("maxScore", maxScore);
            statistics.put("minScore", minScore);
            statistics.put("scoreRanges", scoreRanges);
            
            return Result.success("获取成绩统计信息成功", statistics);
        } catch (Exception e) {
            return Result.error("获取成绩统计信息失败：" + e.getMessage());
        }
    }

    /**
     * 获取用户活跃度统计
     */
    @GetMapping("userActivity")
    public Result<Map<String, Object>> getUserActivityStatistics(@RequestParam(required = false) String identity) {
        try {
            Map<String, Object> statistics = new HashMap<>();
            
            QueryWrapper<TcUser> queryWrapper = new QueryWrapper<>();
            if (identity != null && !identity.trim().isEmpty()) {
                queryWrapper.eq("identity", identity);
            }
            
            List<TcUser> users = userService.list(queryWrapper);
            
            // 按创建时间统计用户注册趋势
            Map<String, Long> registrationTrend = users.stream()
                .collect(Collectors.groupingBy(
                    user -> user.getCreateTime().toString().substring(0, 7), // 按年月分组
                    Collectors.counting()
                ));
            
            statistics.put("totalUsers", users.size());
            statistics.put("registrationTrend", registrationTrend);
            
            return Result.success("获取用户活跃度统计成功", statistics);
        } catch (Exception e) {
            return Result.error("获取用户活跃度统计失败：" + e.getMessage());
        }
    }

    /**
     * 获取作业完成情况统计
     */
    @GetMapping("homeworkCompletion/{classId}")
    public Result<Map<String, Object>> getHomeworkCompletionStatistics(@PathVariable Integer classId) {
        try {
            Map<String, Object> statistics = new HashMap<>();
            
            QueryWrapper<TcHomework> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("class_id", classId);
            List<TcHomework> homeworks = homeworkService.list(queryWrapper);
            
            // 按截止时间统计
            long totalHomework = homeworks.size();
            long expiredHomework = homeworks.stream()
                .filter(h -> h.getDeadline().before(new Date()))
                .count();
            long activeHomework = totalHomework - expiredHomework;
            
            statistics.put("totalHomework", totalHomework);
            statistics.put("activeHomework", activeHomework);
            statistics.put("expiredHomework", expiredHomework);
            
            // 按科目统计
            Map<String, Long> homeworkBySubject = homeworks.stream()
                .collect(Collectors.groupingBy(
                    TcHomework::getTitle, // 这里应该根据实际需求调整
                    Collectors.counting()
                ));
            
            statistics.put("homeworkBySubject", homeworkBySubject);
            
            return Result.success("获取作业完成情况统计成功", statistics);
        } catch (Exception e) {
            return Result.error("获取作业完成情况统计失败：" + e.getMessage());
        }
    }
}

